﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using PcapDotNet.Core;
using PcapDotNet.Packets;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Base;
using PcapDotNet.Analysis;
using System.Net.Sockets;
using WO.Core;
using System.IO;
namespace OpeningAnAdapterAndCapturingThePackets
{
    class Program
    {
        static void Main(string[] args)
        {
            Trace.Listeners.Clear();

            TextWriterTraceListener twtl = new TextWriterTraceListener("log.txt");
            twtl.Name = "TextLogger";
            twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime;

            ConsoleTraceListener ctl = new ConsoleTraceListener(false);
            ctl.TraceOutputOptions = TraceOptions.DateTime;

            Trace.Listeners.Add(twtl);
            Trace.Listeners.Add(ctl);
            Trace.AutoFlush = true;

            Trace.WriteLine("The first line to be in the logfile and on the console.");
            // Send anonymous statistics about the usage of Pcap.Net
            PcapDotNet.Analysis.PcapDotNetAnalysis.OptIn = true;

            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the list
            for (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the device
            using (PacketCommunicator communicator = 
                selectedDevice.Open(65536,                                  // portion of the packet to capture
                                                                            // 65536 guarantees that the whole packet will be captured on all the link layers
                                    PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                    1000))                                  // read timeout
            {
                Console.WriteLine("Listening on " + selectedDevice.Description + "...");

     
                // Compile the filter
                using (BerkeleyPacketFilter filter = communicator.CreateFilter("port 3724"))
                {
                    // Set the filter
                    communicator.SetFilter(filter);
                }

                Console.WriteLine("Listening on " + selectedDevice.Description + "...");

                // start the capture
             
                communicator.ReceivePackets(0, PacketHandler);
          
            }
        }

        // Callback function invoked by Pcap.Net for every incoming packet
        #region Encryption

        public void Encrypt(byte[] Data, int k, int l)
        {
            for (; k < l; k++)
            {
                if (--e < 0)
                {
                    e = random_2.nextInt(100) + 1;
                    f = (byte)random_2.nextInt(256);
                    g = (byte)random_2.nextInt(256);
                }
                Data[k] = (byte)(Data[k] - g);
                Data[k] ^= (byte)f;
            }
        }

        public void Decrypt(byte[] Data)
        {
           // 6D8DD585  75C0850C  CRYPT32.75C0850C


            random_1 = new WO.Core.Encryption.WORandom(0x64df913L);
            random_2 = new WO.Core.Encryption.WORandom(0x64df913L);

            for (int x = 0; x < Data.Length; x++)
            {
                if (--h < 0)
                {
                    h = random_1.nextInt(100) + 1;
                    i = (byte)random_1.nextInt(256);
                    j = (byte)random_1.nextInt(256);
                }
                Data[x] ^= (byte)i;
                Data[x] = (byte)(Data[x] + j);
            }
        }
        private WO.Core.Encryption.WORandom random_1;
        private WO.Core.Encryption.WORandom random_2;
        private int e, f, g, h, i, j;
        #endregion  
   
        private static void PacketHandler(Packet packet)
        {
           
            const int LineLength = 64;
            byte[] packetbyte = new byte[packet.Ethernet.PayloadLength];

            for (int i = 0; i < packet.Ethernet.PayloadLength; i++)
            {

                packetbyte[i] = packet.Ethernet.Payload[i];
            }
            
            byte[] PacketLength = new byte[2];
            Program p = new Program();
            
            PacketLength = packet;
            p.Decrypt(PacketLength);
            PacketReader _len_reader = new PacketReader(PacketLength);

            short size = _len_reader.PopShort();

            byte[] Packet1 = new byte[size];
            Packet1 = packetbyte.ReadBytes(0, size);
            p.Decrypt(Packet1);

          //  HandlePacket(Packet);
    

            Trace.WriteLine(packet.Ethernet.IpV4.Tcp.DestinationPort.ToString());
            Trace.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);
            //Console.WriteLine(pakl);

       

           Trace.WriteLine("Checksum TCP");
            Trace.WriteLine(packet.Ethernet.IpV4.Transport.Checksum);
            Trace.WriteLine("////////");
            Trace.WriteLine("TRANSPORT TO STRING");
            Trace.WriteLine(packet.Ethernet.Payload.SequenceToString());



            Trace.WriteLine("OR THIS////////////////////////////");



Trace.WriteLine(Packet1.SequenceToString());
Trace.WriteLine("////////////////");


        }
    }
}
